#include "usart4.h"

// ?????
u8 USART4_RX_BUF[USART4_RX_BUFF_SIZE];
// ?????
u16 USART4_RX_CNT = 0;
// ?????,1 ?????? @ ??,\r\n ?????
u8 USART4_RX_FLAG = 0;

// USART4 ?????
void USART4_Init(u32 bound)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    // ?? GPIOC ? USART4 ??
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4, ENABLE);

    // PC10 ?? USART4 Tx
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);

    // PC11 ?? USART4 Rx
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOC, &GPIO_InitStructure);

    // USART4 ???
    USART_InitStructure.USART_BaudRate = bound;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_Init(UART4, &USART_InitStructure);

    // ?? USART4 ????
    USART_ITConfig(UART4, USART_IT_RXNE, ENABLE);

    // ?? USART4
    USART_Cmd(UART4, ENABLE);

    // NVIC ??
    NVIC_InitStructure.NVIC_IRQChannel = UART4_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

// USART4 ??????
void UART4_IRQHandler(void)
{
    u8 Res;
    if (USART_GetITStatus(UART4, USART_IT_RXNE) != RESET)
    {
        Res = USART_ReceiveData(UART4);

        if (USART4_RX_CNT == 0 && Res == '@') // ?????? @
        {
            USART4_RX_BUF[USART4_RX_CNT++] = Res;
        }
        else if (USART4_RX_CNT > 0)
        {
            if (USART4_RX_CNT < USART4_RX_BUFF_SIZE - 1)
            {
                USART4_RX_BUF[USART4_RX_CNT++] = Res;
            }
            if (USART4_RX_CNT >= 2 && USART4_RX_BUF[USART4_RX_CNT - 2] == '\r' && USART4_RX_BUF[USART4_RX_CNT - 1] == '\n')
            {
                USART4_RX_FLAG = 1; // ???? @ ??,\r\n ?????,?????
            }
        }
        USART_ClearITPendingBit(UART4, USART_IT_RXNE);
    }
}

